<?php


namespace app\admin\controller\system;

use app\admin\model\user\User;
use app\common\model\Apilist as ApilistModel;
use app\common\model\Apifields as ApifieldlistModel;
use app\common\controller\AdminController;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnotation;
use app\common\service\ApiReturn;
use think\App;
use think\facade\Validate;

/**
 * @ControllerAnnotation(title="接口管理")
 * Class Apilist
 * @package app\admin\controller\system
 */
class Apilist extends AdminController
{

    protected $sort = [
        'sort' => 'desc',
        'id'   => 'desc',
    ];

    protected $allowModifyFields = [
        'needlogin',
    ];

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new ApilistModel();
    }


    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $hash = ApilistModel::where('hash', $post['hash'])->find();
                if (!empty($hash)) {
                    throw new \Exception('hash已存在');
                }
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $hash = uniqid();
        $this->assign('hash', $hash);
        $groups = \app\admin\model\system\SystemApiGroup::where('status', 1)->select();
        $this->assign('groups', $groups);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        $groups = \app\admin\model\system\SystemApiGroup::where('status', 1)->select();
        $this->assign('groups', $groups);
        return $this->fetch();
    }


    /**
     * API接口详情
     * @NodeAnotation(title="接口详情")
     */
    public function apiinfo()
    {
        $hash = input("hash");
        empty($hash) && $this->error('数据不存在');
        $apiinfo = ApilistModel::where(['hash' => $hash])->find();
        if (empty($hash) || empty($apiinfo)) {
            $data = [
                'code' => -1,
                'msg'  => '',
            ];
            return json($data);
        }
        $f_field = ApifieldlistModel::where(['hash' => $hash, 'type' => 1])->select();
        $q_field = ApifieldlistModel::where(['hash' => $hash, 'type' => 0])->select();
        $this->assign('f_field', $f_field);
        $this->assign('q_field', $q_field);
        $this->assign('data', $apiinfo);
        return $this->fetch();
    }

    /**
     * API接口测试
     * @NodeAnotation(title="接口测试")
     */
    public function apitest()
    {
        $hash    = input("hash");
        $version = input("version");
        $apiinfo = ApilistModel::where(['hash' => $hash])->find()->toArray();
        if (!$apiinfo) {
            return ApiReturn::r('-1');
        }
        $data     = request()->post();
        $user_arr = [];
        if (!empty($data["user_id"])) {
            $user = (new \app\admin\model\user\User)->field('id,user_nickname,status,mobile')->find($data["user_id"]);
            if (!$user) {
                $this->error("用户ID不存在");
            }
            $user_arr = $user->toArray();
            unset($data["user_id"]);
        }

        ApiReturn::$user = $user_arr;

        $rule    = ApifieldlistModel::getCacheFields($hash, 0); //获取数据库的 请求字段
        $newRule = ApifieldlistModel::cacheBuildValidateRule($rule);
        if ($newRule) {
            $validate = Validate::rule($newRule);
            if (!$validate->check($data)) {  //验证数据
                return ApiReturn::r('-900', [], $validate->getError()); // 参数错误
            }
        }

        $newData = [];
        foreach ($rule as $item) {
            if ($data[$item['fieldname']] == '') {
                if ($item['default'] != '') {
                    $newData[$item['fieldname']] = $item['default'];
                }
            }
            else {
                $newData[$item['fieldname']] = $data[$item['fieldname']];
            }
        }
        try {
            $apinamearr   = explode('/', $apiinfo['apiname']);
            $apiclassname = ucfirst($apinamearr[0]);
            $apiname      = $apinamearr[1];
            return invoke([
                'app\api\controller\\' . $version . '\\' . $apiclassname,
                $apiname
            ],
                [$newData, $user_arr]);
        } catch (\Exception $e) {
            return ApiReturn::r($e->getCode(), "", $e->getMessage());
        }
    }

}
